/**   
 * @Title: OrderController.java
 * @Package com.wx.controller
 * @Description: 
 * @author wangxiao
 * @date 2017年11月8日 下午2:53:36
 */
package com.wx.controller;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.eova.interceptor.AuthInterceptor;
import com.eova.interceptor.LoginInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Record;
import com.wx.interceptor.ApiInterceptor;
import com.wx.interceptor.JSSDKInterceptor;
import com.wx.model.User;
import com.wx.model.WxAccount;
import com.wx.model.WxAddInfo;
import com.wx.model.WxOrder;
import com.wx.model.WxShop;
import com.wx.model.WxShopOrder;
import com.wx.service.ShopService;
import com.wx.validator.JlfAddOrderValidator;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.util.StrUtil;

/**   
 * @ClassName: OrderController
 * @Description: 
 * @author wangxiao
 * @date 2017年11月8日 下午2:53:36
 */
@Clear({LoginInterceptor.class,AuthInterceptor.class})
public class ShopOrderController extends OrderController{
	static final ShopService shopService = ShopService.me;
	
	@Clear(ApiInterceptor.class)
	public void getSiteScope(){
//		WxAccount wx = getSessionAttr("WXACCOUNT");
//		String lng = getPara("LNG");
//		String lat = getPara("LAT");
//		List<Record>  wxList = ShopService.me.getWxShopListAndTag(wx.getId(), Double.valueOf(lng), Double.valueOf(lat));
//		setAttr("WXSHOPLIST", wxList);
		renderTemplate("/product/template/site_scope.html");
	}
	
	public void getShopByCoordinate(){
		WxAccount wx = getSessionAttr("WXACCOUNT");
		String lng = getPara("LNG");
		String lat = getPara("LAT");
		List<Record>  wxList = ShopService.me.getWxShopListAndTag(wx.getId(), Double.valueOf(lng), Double.valueOf(lat));
		setAttr("WXSHOPLIST", wxList);
		renderTemplate("/wx/add_shoplist.html");
	}
	
	@Before(JSSDKInterceptor.class)
	public void toAddOrderByShop(){
		int addid = getParaToInt("shopid",-1);
		Map addMap = (Map) getSession().getAttribute("ADDMAP");
		if(addid != -1){
			WxShop wxShop = WxShop.dao.findById(addid);
			if(addMap!=null){
				
			}else{
				addMap = new HashMap<>();
			}
			addMap.put("shopname", wxShop.getNAME());
			addMap.put("shopid", wxShop.getID());
			getSession().putValue("ADDMAP", addMap);
			
		}
		WxAccount wx = getSessionAttr("WXACCOUNT");
		renderTemplate(wx.getUrlPath());
	}
	@Override
	public void toUserAdd(){
		//获取地址库信息
		//记录用户已输入的寄件 收件地址
		String str = getPara("orderinfo");
		Map orderMap = JSONUtil.parseObj(str);
		getSession().putValue("ADDMAP", orderMap);
		WxAccount wx = getSessionAttr("WXACCOUNT");
		User user = getSessionAttr("USER");
		List<WxAddInfo> wxList = userAddService.getAllAddInfoByUserId(user.getId());
		setAttr("WXADDLIST", wxList);
		renderTemplate(wx.getUserAddUrl());
	}
	@Override
	public void toEditUserAdd(){
		String state = getPara("state");
		String str = getPara("orderinfo");
		Map orderMap= new HashMap<>();
		if(!StrUtil.isEmpty(str)){
			orderMap= JSONUtil.parseObj(str);
		}
		
		if("3".equals(state)||"4".equals(state)){
			int addid = getParaToInt("addid");
			WxAddInfo wx = userAddService.getWxAddInfoById(addid);
			String receivename = wx.getName();
			String receivephone = wx.getMobile();
			String receivecard = "";
			if(StrUtil.isEmpty(wx.getDefine1())){
				receivecard= "";
			}else{
				receivecard = wx.getDefine1();
			}
			String receiveadd = wx.getPro()+" "+wx.getCity()+" "+wx.getDis()+"^"+wx.getAddress();
			orderMap.put("receivename", receivename);
			orderMap.put("receivephone", receivephone);
			orderMap.put("receiveadd", receiveadd);
			orderMap.put("receivecard", receivecard);
			setAttr("addid", addid);
		}
		getSession().putValue("ADDMAP", orderMap);
		setAttr("sendname", orderMap.get("sendname"));
		setAttr("sendphone", orderMap.get("sendphone"));
		setAttr("sendadd", orderMap.get("sendadd"));
		setAttr("sendcard", orderMap.get("sendcard"));
		setAttr("receivephone", orderMap.get("receivephone"));
		setAttr("receivename", orderMap.get("receivename"));
		setAttr("receiveadd", orderMap.get("receiveadd"));
		setAttr("receivecard", orderMap.get("receivecard"));
		setAttr("state", state);
		WxAccount wx = getSessionAttr("WXACCOUNT");
		if("9".equals(state)){
			renderTemplate("/wx/xieyi.html");
		}else{
			renderTemplate(wx.getAddEditUrl());
		}
		
	}
	@Override
	@Before(JSSDKInterceptor.class)
	public void editAdd(){
//		//获取地址库信息
		String state = getPara("state");
//		String sendname = getPara("sendname");
//		String sendphone = getPara("sendphone");
//		String receivename = getPara("receivename");
//		String receivephone = getPara("receivephone");
//		String receiveadd = getPara("receiveadd");
//		String sendadd = getPara("sendadd");
		String name = getPara("name");
		String mobile = getPara("mobile");
		String address = getPara("address");
		String pro_city_dis = getPara("pro_city_dis");
		String card = getPara("card");
		Map addMap = (Map) getSession().getAttribute("ADDMAP");
		if(addMap==null){
			addMap = new HashMap<>();
		}
		if("3".equals(state)){
			//修改地址库时
			int addid = getParaToInt("addid");
			WxAddInfo wx = userAddService.getWxAddInfoById(addid);
			wx.setName(name);
			wx.setMobile(mobile);
			wx.setAddress(address);
			wx.setDefine1(card);
			String[] pcd = pro_city_dis.split("\\|\\|");
			//解析地址
			if(pcd.length>0){
				for(int i=0;i<pcd.length;i++){
					if(i==0){
						wx.setPro(pcd[i]);
					}else if(i==1){
						wx.setCity(pcd[i]);
					}else if(i==2){
						wx.setDis(pcd[i]);
						break;
					}
				}
			}
			wx.update();
			addMap.put("receivename", wx.getName());
			addMap.put("receivephone", wx.getMobile());
			addMap.put("receivecard", wx.getDefine1());
			addMap.put("receiveadd", wx.getPro()+" "+wx.getCity()+" "+wx.getDis()+"^"+wx.getAddress());
			toUserAdd2();
			return;
		}else{
			if("0".equals(state)){
				addMap.put("sendname", name);
				addMap.put("sendcard", card);
				addMap.put("sendphone", mobile);
				addMap.put("sendadd", pro_city_dis +"^"+address);
				String isdefault = getPara("isdefault");
				if("on".equals(isdefault)){
					//保存成默认寄件地址
					User user = getSessionAttr("USER");
					//判断寄件地址是否改变
					WxAddInfo sendAdd = userAddService.getUserDefaultSendAdd(user.getId());
					if(sendAdd==null||(!address.equals(sendAdd.getAddress())||!mobile.equals(sendAdd.getMobile())||!name.equals(sendAdd.getName())||!card.equals(sendAdd.getDefine1()))){
						WxAddInfo wx = new WxAddInfo();
						String[] pcd = pro_city_dis.split("\\|\\|");
						wx.setAddress(address);
						wx.setCreateDate(new Date());
						wx.setIsdefault("1");
						wx.setMobile(mobile);
						wx.setName(name);
						wx.setDefine1(card);
						wx.setType("2");
						wx.setUserId(user.getId());
						//解析地址
						if(pcd.length>0){
							for(int i=0;i<pcd.length;i++){
								if(i==0){
									wx.setPro(pcd[i]);
								}else if(i==1){
									wx.setCity(pcd[i]);
								}else if(i==2){
									wx.setDis(pcd[i]);
									break;
								}
							}
						}
						userAddService.setDefaultSendAdd(wx, user);
					}
				}
			}else if("1".equals(state)){
				addMap.put("receivename", name);
				addMap.put("receivephone", mobile);
				addMap.put("receivecard", card);
				addMap.put("receiveadd", pro_city_dis +"^"+address);
			}else if("2".equals(state)){
				//添加地址库
				User user = getSessionAttr("USER");
				WxAddInfo wx = new WxAddInfo();
				String[] pcd = pro_city_dis.split("\\|\\|");
				wx.setAddress(address);
				wx.setCreateDate(new Date());
				wx.setMobile(mobile);
				wx.setName(name);
				wx.setDefine1(card);
				wx.setType("1");
				wx.setUserId(user.getId());
				//解析地址
				if(pcd.length>0){
					for(int i=0;i<pcd.length;i++){
						if(i==0){
							wx.setPro(pcd[i]);
						}else if(i==1){
							wx.setCity(pcd[i]);
						}else if(i==2){
							wx.setDis(pcd[i]);
							break;
						}
					}
				}
				wx.save();
				toUserAdd2();
				return;
			}
		}
		getSession().putValue("ADDMAP", addMap);
		setAttr("state", state);
		WxAccount wx = getSessionAttr("WXACCOUNT");
		renderTemplate(wx.getUrlPath());
	}
	
	/**
	 * 
	 * @throws UnsupportedEncodingException 
	 * @Title: addOrder
	 * @Description:下单
	 */
	@Override
	@Before(JlfAddOrderValidator.class)
	public void addOrder() throws UnsupportedEncodingException{
		
		//获取请求参数
		WxAccount wx = getSessionAttr("WXACCOUNT");
		User user = getSessionAttr("USER");
		int shopid = getParaToInt("shopid");
		WxShop ws = WxShop.dao.findById(shopid);
		//获取省市区
		WxOrder order =getModel(WxOrder.class);
		//判断单号是否重复
		List orderList = WxOrder.dao.find("select * from wx_order d where d.order_no = ?",order.getOrderNo());
		if(orderList.size()>0){
			renderJson(Ret.fail("ERRMESSAGE", "订单号系统内已存在，请跟换订单号!"));
		}else{
			order.setSendAdd(ws.getADDRESS());
			order.setSendPro(ws.getPRO());
			order.setSendCity(ws.getCITY());
			order.setSendDis(ws.getDIS());
			order.setSendMobile(ws.getContactTel());
			order.setSendName(ws.getCONTACT());
			order.setAppid(wx.getAppid());
			order.setUserid(user.getId());
			order.setCreateTime(new Date());
			order.setStatus("0");
			
			
			Double dd =shopService.getXyFrom(ws.getLAT(),ws.getLNG(), order.getReceivePro()+order.getReceiveCity()+order.getReceiveDis()+order.getReceiveAdd());
//			Double dd =shopService.getXyFrom(ws.getLAT()+","+ws.getLNG(), order.getReceivePro()+order.getReceiveCity()+order.getReceiveDis()+order.getReceiveAdd());
			if(dd>6000){
				if(dd ==9898989.00){
					renderJson(Ret.fail("ERRMESSAGE", "根据您输入的地址无法匹配距离!"));
				}else{
					renderJson(Ret.fail("ERRMESSAGE", "收件地址距离门店超过5公里，无法配送!"));
				}
			}else{
				order.setRemark("配送距离:"+dd+"米;"+order.getRemark());
				String str = this.getTempMess(order, wx.getOrderTempKey());
				Map paramMap = new HashMap<>();
//				paramMap.put("Constant_id", "createOrder");
				paramMap.put("content", str);
				paramMap.put("callback", "");
				log.info(str);
				String response = HttpUtil.post(wx.getAddOrderUrl(), paramMap);
				Map result = new HashMap<>();
				log.info(response);
				result = JSONUtil.parseObj(response.substring(1, response.length()-1));
				if("SUCCESS".equals(result.get("returnType"))){
					order.setOrderNo((String)result.get("returnValue"));
					order.setShopid(shopid);
					order.save();
					WxShopOrder wso = new WxShopOrder();
					wso.setORDERID(order.getId());
					wso.setSHOPID(shopid);
					wso.save();
					renderJson(Ret.ok("ORDERNO", order.getOrderNo()));
				}else{
					renderJson(Ret.fail("ERRMESSAGE", result.get("returnValue")));
				}
			}
		}
	}
}